/*
 * @Descripttion: GGB
 * @version: 1.0
 * @Author: GGB
 * @Date: 2021-08-18 11:13:41
 * @LastEditors: GGB
 * @LastEditTime: 2021-08-19 11:56:01
 */

import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_data_center/components/custom_btn.dart';
import 'package:flutter_data_center/utills/color_utils.dart';
import 'package:flutter_data_center/utills/toast_utils.dart';
import 'components/choose_audio.dart';
import 'components/custom_textfield_widget.dart';
import 'components/file_list.dart';
import 'components/push_task.dart';

class BroadcastAddScreen extends StatefulWidget {
  const BroadcastAddScreen({Key key}) : super(key: key);
  static String routeName = "/broadcast_add";

  @override
  _BroadcastAddScreenState createState() => _BroadcastAddScreenState();
}

class _BroadcastAddScreenState extends State<BroadcastAddScreen> {
  FocusNode _taskFocusNode = new FocusNode();
  FocusNode _timeFocusNode = new FocusNode();
  TextEditingController _taskEditController = new TextEditingController();
  TextEditingController _timeEditController = new TextEditingController();

  // List<String> _list = [
  //   "为您更好的体验应用，所以需要获取本地文档权限",
  //   "您已拒绝权限，所以无法保存您的一些偏好设置，将无法使用APP",
  //   "您已拒绝权限，请在设置中心中同意APP的权限请求",
  //   "其他错误"
  // ];
  List<PlatformFile> files = [];
  String directoryPath;
  String extension;
  bool loadingPath = false;
  bool multiPick = true;
  FileType pickingType = FileType.audio;

  // 打开文件管理器

  void _openFileExplorer() async {
    print("点击");
    setState(() => loadingPath = true);
    try {
      directoryPath = null;
      files = (await FilePicker.platform.pickFiles(
        type: pickingType,
        allowMultiple: multiPick,
        onFileLoading: (FilePickerStatus status) => print(status),
        allowedExtensions: (extension?.isNotEmpty ?? false)
            ? extension.replaceAll(' ', '').split(',')
            : null,
      ))
          ?.files;
    } on PlatformException catch (e) {
      print("Unsupported operation" + e.toString());
    } catch (ex) {
      print(ex);
    }
    if (!mounted) return;
    setState(() {
      loadingPath = false;
      files = files;
    });
  }

  // 清除文件缓存
  void _clearCachedFiles() {
    FilePicker.platform.clearTemporaryFiles().then((result) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          backgroundColor: result ? Colors.green : Colors.red,
          content: Text((result
              ? 'Temporary files removed with success.'
              : 'Failed to clean temporary files')),
        ),
      );
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    // _clearCachedFiles();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: buildAppBar(),
      body: SingleChildScrollView(
        child: Padding(
          padding: EdgeInsets.symmetric(horizontal: 20, vertical: 20),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                "任务名称",
                style: TextStyle(
                  fontSize: 18,
                ),
              ),
              SizedBox(height: 10),
              buildTaskName(context),
              SizedBox(
                height: 35,
              ),
              Text(
                "时间",
                style: TextStyle(
                  fontSize: 18,
                ),
              ),
              SizedBox(height: 10),
              buildTimePicker(context),
              SizedBox(
                height: 35,
              ),
              Text(
                "音频文件",
                style: TextStyle(
                  fontSize: 18,
                ),
              ),
              SizedBox(height: 10),
              ChooseAudio(onTap: () => _openFileExplorer()),
              SizedBox(height: 10),
              if (files.length > 0)
                FileList(
                  files: files,
                  onDel: (index) {
                    files.removeAt(index);
                    setState(() {});
                  },
                ),
              SizedBox(height: 35),
              CustomBtn(
                text: "发布任务",
                onTap: () => submitFunction,
                primary: gColor("#08D187"),
                boxShadows: [
                  BoxShadow(
                    offset: Offset(0, 0),
                    blurRadius: 30,
                    color: Color.fromRGBO(8, 209, 135, 0.25),
                  ),
                ],
              ),
              // 发布任务
              SizedBox(height: 46),
            ],
          ),
        ),
      ),
    );
  }

  TextFieldWidget buildTimePicker(BuildContext context) {
    return TextFieldWidget(
      // 提交事件
      submit: (value) {
        if (value == null) {
          ToastUtils.showToast("请选择时间");
          return;
        }
        _timeFocusNode.unfocus();
      },
      onTap: () async {
        var result = await showTimePicker(
          context: context,
          initialTime: TimeOfDay.now(),
        );
        _timeEditController.text = result.format(context);
      },
      controller: _timeEditController,
      focusNode: _timeFocusNode,
      // 右侧图标点击事件
      obscureText: false,
      readOnly: true,
    );
  }

  TextFieldWidget buildTaskName(BuildContext context) {
    return TextFieldWidget(
      submit: (value) {
        if (value == null) {
          ToastUtils.showToast("请输入任务名称");
          //手机号输入框重新获取焦点
          FocusScope.of(context).requestFocus(_taskFocusNode);
          return;
        }
        //手机号输入框失去焦点
        _taskFocusNode.unfocus();
        //密码输入框获取焦点
        FocusScope.of(context).requestFocus(_taskFocusNode);
      },
      focusNode: _taskFocusNode,
      controller: _taskEditController,
      obscureText: false,
    );
  }

  AppBar buildAppBar() {
    return AppBar(
      title: Text("添加广播任务"),
      backgroundColor: Colors.white,
      elevation: 0,
    );
  }

  // 提交任务
  void submitFunction() async {
    //获取用户名
    // String task = _taskEditController.text;
  }
}
